package com.example.app01

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity

class EditInfoActivity : AppCompatActivity() {

    private lateinit var etName: EditText
    private lateinit var etGender: EditText
    private lateinit var etPhone: EditText
    private lateinit var btnSave: Button
    private lateinit var btnCancel: Button

    private var hasChanges = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_info)

        initViews()
        loadCurrentInfo()
        setupClickListeners()
        setupBackPressHandler()
    }

    private fun initViews() {
        etName = findViewById(R.id.etName)
        etGender = findViewById(R.id.etGender)
        etPhone = findViewById(R.id.etPhone)
        btnSave = findViewById(R.id.btnSave)
        btnCancel = findViewById(R.id.btnCancel)

        // 添加文本变化监听
        etName.setOnFocusChangeListener { _, hasFocus -> if (!hasFocus) checkChanges() }
        etGender.setOnFocusChangeListener { _, hasFocus -> if (!hasFocus) checkChanges() }
        etPhone.setOnFocusChangeListener { _, hasFocus -> if (!hasFocus) checkChanges() }
    }

    private fun loadCurrentInfo() {
        etName.setText(intent.getStringExtra("name"))
        etGender.setText(intent.getStringExtra("gender"))
        etPhone.setText(intent.getStringExtra("phone"))
    }

    private fun setupClickListeners() {
        btnSave.setOnClickListener {
            if (validateInput()) {
                saveChanges()
            }
        }

        btnCancel.setOnClickListener {
            handleCancel()
        }
    }

    private fun setupBackPressHandler() {
        val onBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                handleCancel()
            }
        }

        onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
    }

    private fun checkChanges() {
        val originalName = intent.getStringExtra("name") ?: ""
        val originalGender = intent.getStringExtra("gender") ?: ""
        val originalPhone = intent.getStringExtra("phone") ?: ""

        hasChanges = etName.text.toString() != originalName ||
                etGender.text.toString() != originalGender ||
                etPhone.text.toString() != originalPhone
    }

    private fun validateInput(): Boolean {
        if (TextUtils.isEmpty(etName.text)) {
            etName.error = "请输入姓名"
            etName.requestFocus()
            return false
        }

        if (TextUtils.isEmpty(etGender.text)) {
            etGender.error = "请输入性别"
            etGender.requestFocus()
            return false
        }

        if (TextUtils.isEmpty(etPhone.text)) {
            etPhone.error = "请输入电话号码"
            etPhone.requestFocus()
            return false
        }

        if (!etPhone.text.toString().matches(Regex("\\d{11}"))) {
            etPhone.error = "请输入11位手机号码"
            etPhone.requestFocus()
            return false
        }

        return true
    }

    private fun saveChanges() {
        val resultIntent = Intent()
        resultIntent.putExtra("name", etName.text.toString())
        resultIntent.putExtra("gender", etGender.text.toString())
        resultIntent.putExtra("phone", etPhone.text.toString())
        setResult(Activity.RESULT_OK, resultIntent)
        finish()
    }

    private fun handleCancel() {
        if (hasChanges) {
            // 如果有未保存的更改，显示确认对话框
            androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("确认退出")
                .setMessage("您有未保存的更改，确定要退出吗？")
                .setPositiveButton("保存并退出") { _, _ ->
                    if (validateInput()) {
                        saveChanges()
                    }
                }
                .setNegativeButton("直接退出") { _, _ ->
                    setResult(Activity.RESULT_CANCELED)
                    finish()
                }
                .setNeutralButton("取消", null)
                .show()
        } else {
            setResult(Activity.RESULT_CANCELED)
            finish()
        }
    }
}